const { Op, where } = require("sequelize");
const sequelize = require("../../model/index")
const friendMessage = require('../../model/friendMessage');
const userGroupMessage = require("../../model/userGroupMessage");
const userFriendMid = require("../../model/userFriendMid")
const UserInfo = require("../../model/userinfo")
const groupMessage = require('../../model/groupMessage');
const userGroup = require('../../model/userGroup');
const { ServerGetFriendsList } = require("../friends")
const { ServerGetUserInfo } = require("../user")
module.exports = {
  Private: {
    ServersetMessage: async ({ messageId, messageContent, messageType, messageSendType }) => {
      const friendMessageres = await friendMessage.create({ messageId, messageContent, messageType, messageSendType });
      if (friendMessageres) {
        return {
          isok: 1,
          message: "发送成功",
          data: friendMessageres
        }
      }
      return {
        isok: 0,
        message: "发送失败",
        data: {}
      }
    }
  },
  ServerGetMessageList: async (userId) => {
    const GetFriendsListres = await ServerGetFriendsList(userId);
    if (GetFriendsListres.isok) {
      const friendliest = GetFriendsListres.data.filter(item => item.showMessage);
      const lastFriendMessageRes = await friendMessage.findAll({
        where: {
          id: {
            [Op.in]: friendliest.map(item => item.messageLastdate)
          }
        },
        raw: true
      })
      const res = friendliest.map((data) => {
        const lastFriendMessage = lastFriendMessageRes.find((item) => data.messageLastdate == item.id)
        return {
          id: data.messageId,
          messageType: lastFriendMessage.messageType,
          message: lastFriendMessage.messageContent,
          lastMessageTime: lastFriendMessage.createdAt,
          name: data.commendName ? data.commendName : data.userName,
          avatar: data.userAvatar,
          noMessageNum: data.noMessageNum,
          type: "friend"
        }
      })
      if (res.length) {
        return {
          isok: 1,
          data: res,
          message: "查询成功"
        }
      }
    }
    return {
      isok: 1,
      data: [],
      message: "暂无数据"
    }
  },
  ServerReadMessage: async ({ messageId, type, userId }) => {
    let res;
    if (type == 'group') {
      res = await userGroupMessage.update({ noMessageNum: 0 }, {
        where: {
          userId,
          groupId: messageId
        }
      }, { raw: true })
    } else {
      const FriendMidres = await userFriendMid.findOne({
        where: {
          id: messageId
        }
      }, { raw: true })
      if (FriendMidres) {
        if (userId == FriendMidres.friendUserId1) {
          res = await userFriendMid.update({ noMessageNum1: 0 }, {
            where: {
              id: messageId
            }
          })
        } else {
          res = await userFriendMid.update({ noMessageNum2: 0 }, {
            where: {
              id: messageId
            }
          })
        }
      } else {
        return {
          isok: 0,
          message: "服务器逻辑出错了",
          data: false
        }
      }
    }
    if (res) {
      return {
        isok: 1,
        message: "成功",
        data: true
      }
    }
    return {
      isok: 0,
      message: "服务器逻辑出错了",
      data: false
    }
  },
  ServerGetFriendsMessage: async ({ messageId, pageSize, startId, userId }) => {
    try {
      const userfriends = await userFriendMid.findOne({
        where: {
          id: messageId
        }
      }, { raw: true });
      const friendsUserId = userfriends.friendUserId1 === userId ? userfriends.friendUserId2 : userfriends.friendUserId1;
      const commendName = userfriends.friendUserId1 === userId ? userfriends.commendName1 : userfriends.commendName2;
      const friendsInfo = await UserInfo.findOne({
        where: {
          id: friendsUserId
        }
      }, { raw: true })
      let countt;
      let messagelist;
      if (startId) {
        const { count, rows } = await friendMessage.findAndCountAll({
          where: {
            [Op.and]: {
              messageId: userfriends.friendMessageId,
              id: {
                [Op.lt]: startId
              }
            },
          },
          order: [
            ['createdAt', 'DESC']
          ],
          limit: pageSize,
        }, { raw: true })
        countt = rows.length;
        messagelist = rows
      } else {
        const { count, rows } = await friendMessage.findAndCountAll({
          where: {
            [Op.and]: {
              messageId: userfriends.friendMessageId,
            },
          },
          order: [
            ['createdAt', 'DESC']
          ],
          limit: pageSize,
        }, { raw: true })
        countt = rows.length;
        messagelist = rows
      }
      const friendsmessaglist = messagelist.filter(item => item.messageSendType);
      const systemsmessagelist = messagelist.filter(item => !item.messageSendType);
      const messagesfriends = friendsmessaglist.map(item => {
        const messages = {
          id: item.messageUserId,
          messageId: item.id,
          name: commendName ? commendName : friendsInfo.userName,
          avatar: friendsInfo.userAvatar,
          content: item.messageContent,
          messageType: item.messageType,
          messageSendType: item.messageSendType,
          createdAt: item.createdAt,
          messageStatus: item.messageStatus,
        }
        return messages
      })
      return {
        isok: 1,
        message: "获取成功",
        data: {
          total: countt,
          list: [...messagesfriends, ...systemsmessagelist.map(data => {
            return {
              messageId: data.id,
              content: data.messageContent,
              messageSendType: data.messageSendType,
              createdAt: data.createdAt,
              messageType: data.messageType
            }
          })].sort((a, b) => {
            return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
          })
        }
      }
    } catch (error) {
      console.log(error);
      return {
        isok: 0,
        message: "获取失败",
      }
    }
  },
  ServerSendMessageToFriend: async ({ friendId, userId, content, messageType = "data", messageSendType = 1 }) => {
    const t = await sequelize.transaction();
    try {
      const userFriendres = await userFriendMid.findOne({
        where: {
          id: friendId
        }
      }, {
        raw: true,
        transaction: t
      });
      const messageId = userFriendres.friendMessageId;
      const message = await friendMessage.create({
        messageId: messageId,
        messageUserId: userId,
        messageType: messageType,
        messageContent: content,
        messageSendType: messageSendType
      }, {
        transaction: t
      })
      let updatauserFriendMid
      if (message) {
        if (userFriendres.friendUserId1 == userId) {
          updatauserFriendMid = await userFriendMid.update({
            noMessageNum2: userFriendres.noMessageNum2 + 1,
            messageLastdate: message.id,
          }, {
            where: {
              id: friendId
            }
          }, {
            transaction: t
          })
        } else {
          updatauserFriendMid = await userFriendMid.update({
            noMessageNum1: userFriendres.noMessageNum1 + 1,
            messageLastdate: message.id
          }, {
            where: {
              id: friendId
            }
          }, {
            transaction: t
          })
        }
      }
      const friendres = await userFriendMid.findOne({
        where: {
          id: friendId
        }
      }, { raw: true })
      if (updatauserFriendMid.length) {
        await t.commit();
        const frienduserId = userFriendres.friendUserId1 == userId
        const userInfo = await ServerGetUserInfo(frienduserId ? userFriendres.friendUserId2 : userFriendres.friendUserId1, true);
        const friendsUser = {}
        if (userInfo) {
          friendsUser.name = frienduserId ? userFriendres.commendName2 ?? userInfo.data.userName : userFriendres.commendName1 ?? userInfo.data.userName;
          friendsUser.id = frienduserId ? userFriendres.friendUserId1 : userFriendres.friendUserId2;
          friendsUser.content = content;
          friendsUser.messageSendType = messageSendType;
          friendsUser.messageType = messageType;
          friendsUser.avatar = userInfo.data.userAvatar;
          friendsUser.createdAt = message.createdAt;
          friendsUser.messageId = friendId;
          friendsUser.friendId = frienduserId ? userFriendres.friendUserId2 : userFriendres.friendUserId1;
        }
        return {
          isok: 1,
          message: "发送成功",
          data: friendsUser,
          lastMessageTime: message.createdAt,
          updatauserFriendMid: friendres
        }
      } else {
        return {
          isok: 0,
          message: "",
          data: {}
        }
      }
    } catch (error) {
      console.log(error);
      // 回滚事务
      await t.rollback();
      return {
        isok: 0,
        message: "发送失败",
        data: {}
      }
    }
  },
  ServerRecallMessage: async ({ messageId, type, userId }) => {
    try {
      if (type === "friend") {
        const message = await friendMessage.findOne({
          where: {
            id: messageId,
            messageUserId: userId,
          },
          raw: true
        });

        if (!message) {
          return {
            isok: 0,
            message: "找不到可撤回的消息或无权限撤回",
            data: {}
          };
        }

        const updateResult = await friendMessage.update(
          {
            messageStatus: 0
          },
          {
            where: {
              id: messageId,
              messageUserId: userId
            }
          }
        );

        if (updateResult[0] === 0) {
          return {
            isok: 0,
            message: "撤回消息失败",
            data: {}
          };
        }

        const friendMid = await userFriendMid.findOne({
          where: {
            friendMessageId: message.messageId
          },
          raw: true
        });

        if (!friendMid) {
          return {
            isok: 0,
            message: "找不到对应的会话",
            data: {}
          };
        }

        const friendUserId = friendMid.friendUserId1 === userId
          ? friendMid.friendUserId2
          : friendMid.friendUserId1;

        return {
          isok: 1,
          message: "消息已撤回",
          data: {
            messageId: messageId,
            originMessage: message,
            type: "friend",
            friendUserId: friendUserId
          }
        };
      }
      else if (type === "group") {
        const message = await groupMessage.findOne({
          where: {
            id: messageId,
            messageUserId: userId,
            messageStatus: 1
          },
          raw: true
        });

        if (!message) {
          return {
            isok: 0,
            message: "找不到可撤回的消息或无权限撤回",
            data: {}
          };
        }

        const updateResult = await groupMessage.update(
          {
            messageStatus: 0,
          },
          {
            where: {
              id: messageId,
              messageUserId: userId
            }
          }
        );

        if (updateResult[0] === 0) {
          return {
            isok: 0,
            message: "撤回消息失败",
            data: {}
          };
        }

        const group = await userGroup.findOne({
          where: {
            id: message.groupId
          },
          raw: true
        });

        if (!group) {
          return {
            isok: 0,
            message: "找不到对应的群组",
            data: {}
          };
        }

        return {
          isok: 1,
          message: "消息已撤回",
          data: {
            messageId: messageId,
            originMessage: message,
            type: "group",
            group: group
          }
        };
      } else {
        return {
          isok: 0,
          message: "不支持的消息类型",
          data: {}
        };
      }
    } catch (error) {
      console.error("撤回消息出错:", error);
      return {
        isok: 0,
        message: "服务器错误",
        data: {}
      };
    }
  }
}